package server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;

import java.util.Date;

public class MyServerBoot {

    private static final int PORT = 9998;
    public static void main(String[] args) {
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        final ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap
                .group(boosGroup, workerGroup)
                .channel(NioServerSocketChannel.class)

//                .option(ChannelOption.SO_BACKLOG, 1024)
//                .childOption(ChannelOption.SO_KEEPALIVE, true)
//                .childOption(ChannelOption.TCP_NODELAY, true)

                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel ch) {
                        //按照字节长度拆分
                        ch.pipeline().addLast(new FixedLengthFrameDecoder(40));

                        //MaxLength:一行最大的长度,超过长度会抛异常  stripDelimiter:是否去除换行符   failFast 是否快速失败
                       // ch.pipeline().addLast(new LineBasedFrameDecoder(1024,true,true));

                        //自定义分隔符解码
                        ByteBuf delimiter = Unpooled.copiedBuffer("$".getBytes());
                        ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));

                        //长度域拆包 maxFrameLength:数据总长度的最大长度 lengthFieldOffset:数据偏移量(等于舍弃多少个字节)  lengthFieldLength 后面数据的长度占字节数
                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,7,4));
                        ch.pipeline().addLast(new MyDecoder());
                    }
                });
        bind(serverBootstrap, PORT);
    }


    private static void bind(final ServerBootstrap serverBootstrap, final int port) {
        serverBootstrap.bind(port).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println(new Date().toString() + ": 端口[" + port + "]绑定成功!");
            } else {
                System.err.println("端口[" + port + "]绑定失败!");
            }
        });
    }

}
